<!--
  @Descripttion：常见问题楼层配置子项
  @Author：zqy
  @Date：2020-08-03 13:11:03
  @Last Modified by：zqy
  @Last Modified time：2020-08-03 13:11:03
-->
<template>
  <div class="item-list-page">
    <div class="item-title">
      <div><strong>配置项</strong></div>
      <div>
        <el-button v-if="maxCount===0 || formData.listData.length < maxCount" type="primary" size="mini" @click="handleAdd">添加</el-button>
        <!-- <el-button size="mini" @click="handleDelete">删除</el-button> -->
      </div>
    </div>
    <div class="table-list-box input-center floor-item-table">
      <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="0">
        <el-table
          style="width: 100%"
          :data="formData.listData"
          header-row-class-name="table-list-header"
          row-key="itemSort"
          highlight-current-row
          border
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="maxCount===0" type="selection" width="40" />
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="关联内容">
            <template v-slot="{row,$index}">
              <div v-if="!readonly" class="table-form-item">
                <el-form-item
                  :prop="'listData.'+$index+'.contentTitle'"
                  :rules="[{ required:true, message: '必选', trigger: ['change', 'blur'] }]"
                >
                  <el-input v-model="row.contentTitle" placeholder="请选择" @focus="handleOpenPageDlg($index)">
                    <i slot="suffix" class="el-input__icon el-icon-search" @click.self="handleOpenPageDlg($index)" />
                  </el-input>
                </el-form-item>
              </div>
              <div v-else class="table-form-item">
                {{ row.contentTitle }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90">
            <template v-slot="{row,$index}">
              <el-button type="text" size="mini" style="padding-left:0 !important" @click="handleDel($index)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-form>
    </div>
    <content-page-dlg
      v-if="visibleActPage"
      :visible.sync="visibleActPage"
      @change="handlePageChange"
      @close="handlePageDlgClose"
    />
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import ContentPageDlg from '../../component/ContentPageDlg'
export default {
  name: 'FloorQuestionItemList',
  components: { ContentPageDlg },
  props: {
    readonly: {
      type: Boolean,
      default: false
    }, // 是否只读
    layoutData: {
      type: [String, Object],
      default: ''
    }, // 当前所选中的楼层布局
    itemList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      imgPrefix: process.env.VUE_APP_Img_prefix,
      newObj: {
        itemSort: null, // 序号
        itemPic: '', // 图片地址或商品图片地址（相对地址）
        imageFullPath: '', // 图片绝对路径（完整显示图片的地址）
        contentId: '', // 内容ID
        contentTitle: '' // 内容标题
      },
      formData: {
        listData: []
      },
      formRules: {
        itemPic: [
          { required: true, message: '必传', trigger: 'blur' }
        ]
      },
      selectedRows: [], // 当前选中行
      optIndex: -1, // 当前操作的行(用户头像与弹窗选择的回调处理)
      visibleActPage: false, // 是否打开关联页选择弹窗
      pageData: '' // 当前所选中的关联页数据
    }
  },

  computed: {
    maxCount() {
      return this.layoutData.maxCount || 0
    },
    minCount() {
      return this.layoutData.minCount || 0
    }
  },
  watch: {
    itemList: {
      handler(val, oldVal) {
        this.initTableData(val || [])
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.initTableData(this.itemList)
  },

  mounted() {
    /* this.$nextTick(() => {
      this.rowDrop()
    }) */
  },
  methods: {
    // 行拖拽排序
    rowDrop() {
      const el = document.querySelector('.floor-item-table .el-table__body-wrapper tbody')
      Sortable.create(el, {
        disabled: this.readonly, // 是否禁用拖拽
        // handle: '.allowDrop', // 指定行可拖拽
        ghostClass: 'selected-highlight', // 拖拽样式
        animation: 300, // 拖拽延时
        // 拖拽开始
        onStart: (e) => {},
        // 拖拽移动
        onMove: (e) => {},
        // 拖拽结束
        onEnd: ({ newIndex, oldIndex }) => {
          if (newIndex === oldIndex) return
          const currRow = this.formData.listData.splice(oldIndex, 1)[0]
          this.formData.listData.splice(newIndex, 0, currRow)
          this.optIndex = -1
          const listData = this.formData.listData.map((list, index) => {
            list.itemSort = index + 1
            return list
          })
          this.$set(this.formData, 'listData', listData)
        }
      })
    },
    // 初始化表格数据
    initTableData(data) {
      const newRow = Object.assign({}, this.newObj)
      if (!data || data.length === 0) {
        this.formData.listData = []
        if (this.maxCount === 0 || this.minCount === 1) {
          this.formData.listData.push({ ...newRow, ...{ itemSort: 1 }})
        } else {
          for (let i = 0; i < this.minCount; i++) {
            this.formData.listData.push({ ...newRow, ...{ itemSort: i + 1 }})
          }
        }
        return
      }
      this.formData.listData = data.map((d, index) => {
        d.itemSort = index
        d.imageFullPath = this.formatImageUrl(d.coverUrl)
        if (d.contentId && d.contentTitle) {
          d.relativePage = {
            id: d.contentId,
            name: d.contentTitle
          }
        } else {
          d.contentId = ''
          d.contentTitle = ''
          d.relativePage = ''
        }
        return { ...newRow, ...d }
      })
    },
    // 新增
    handleAdd() {
      if (this.maxCount > 0 && this.formData.listData.length >= this.maxCount) {
        this.$message.warning(`配置项不能超过${this.maxCount}个`)
        return
      }
      const newRow = Object.assign({}, this.newObj)
      newRow.itemSort = this.formData.listData.length + 1
      this.formData.listData.push(newRow)
    },
    // 单选行
    handleCurrentChange(row) {
      // this.optIndex = row
    },
    // 多选操作
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    // 批量删除
    handleDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择删除项')
        return
      }
      this.selectedRows.forEach(row => {
        const index = this.formData.listData.findIndex(v => v.itemSort === row.itemSort)
        this.handleDel(index)
      })
      this.selectedRows = []
    },
    // 处理删除行
    handleDel(index) {
      this.formData.listData.splice(index, 1)
    },
    // 打开活动页面选择窗口
    handleOpenPageDlg(index) {
      this.optIndex = index
      this.visibleActPage = true
    },
    // 活动页面选择处理
    handlePageChange(rows) {
      const editRow = this.formData.listData[this.optIndex]
      const row = rows && rows.length ? rows[0] : ''
      const newData = Object.assign({}, editRow)
      newData.contentId = row.id || ''
      newData.contentTitle = row.title || ''
      newData.relativePage = row
      this.$set(this.formData.listData, this.optIndex, newData)
    },
    handlePageDlgClose() {
      const editRow = this.formData.listData[this.optIndex]
      if (!editRow.relativePage || !editRow.relativePage.id) {
        editRow.contentId = ''
        editRow.contentTitle = ''
        editRow.relativePage = ''
        this.$set(this.formData.listData, this.optIndex, editRow)
      }
    },
    /**
     * 验证当前表单数据
     * @returns {Boolean} 是否通过验证：true 通过，false 未通过
     * */
    async validateForm() {
      return new Promise((resolve, reject) => {
        if (this.formData.listData.length === 0) {
          reject(`至少配置1个内容项，否则不可保存`)
          return
        }
        this.$refs['refForm'].validate((valid) => {
          if (valid) {
            if (this.maxCount > 0 && this.formData.listData.length > this.maxCount) {
              reject(`内容数量不能超过${this.maxCount}个`)
              return
            }
            const formData = JSON.parse(JSON.stringify(this.formData.listData))
            resolve(formData)
          } else {
            reject('配置项未填写完整')
          }
        })
      })
    }
  }
}
</script>
<style lang='scss' scoped>

.item-list-page{
  .item-title{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.table-form-item{
  padding: 15px 0;
  text-align: center;
  /deep/.el-form-item--mini.el-form-item{
    margin-bottom: 0;
  }
}

</style>
